package com.xr50.user.conf;

import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.alibaba.fastjson.JSON;
import com.xr50.common.Result;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
public class UserBlockExceptionHandler implements BlockExceptionHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        Result result = new Result();

        if (e instanceof FlowException) {
            result.setCode("2001");
            result.setMsg("限流异常");
        }else if (e instanceof DegradeException) {
            result.setCode("2002");
            result.setMsg("降级异常");
        }else if (e instanceof ParamFlowException) {
            result.setCode("2003");
            result.setMsg("参数限流异常");
        }else if (e instanceof SystemBlockException) {
            result.setCode("2004");
            result.setMsg("系统负载异常");
        }else if (e instanceof AuthorityException) {
            result.setCode("2005");
            result.setMsg("授权异常");
        }

        httpServletResponse.setStatus(200);
        httpServletResponse.setHeader("Content-Type","application/json;charset=UTF-8");
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}
